package com.polaris.live.ui.login

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.polaris.live.adapter.AreaCodeAdapter
import com.polaris.live.common.mvvm.base2.BaseVbActivity
import com.polaris.live.databinding.ActivityAreaCodeBinding
import com.polaris.live.resp.back_resp.AreaCodeResp
import com.polaris.live.viewmodel.login.AreaCodeViewModel

/**
 * 区号选择页面
 *
 * @author Created by 半仙 on 2023/8/15/015 17:10
 */
class AreaCodeActivity : BaseVbActivity<AreaCodeViewModel, ActivityAreaCodeBinding>() {

    private val list = mutableListOf<AreaCodeResp>()
    private var initialList = emptyArray<String>() //首字母
    private var stringExtra = ""

    private val mAdapter: AreaCodeAdapter by lazy {
        AreaCodeAdapter()
    }

    override fun initView(savedInstanceState: Bundle?) {
        stringExtra = intent.getStringExtra("countryCode").toString()

        mBinding.recycler.apply {
            layoutManager = LinearLayoutManager(this@AreaCodeActivity, RecyclerView.VERTICAL, false)
            adapter = mAdapter
        }

        initData()

        mBinding.sidebar.setSideBarLayout { word ->
            var scrollToIndex = -1
            for ((index, areaCodeResp) in list.withIndex()) {
                if (areaCodeResp.firstLetter == word) {
                    if (list[0].firstLetter != "A" && list[0].firstLetter == word) {
                        if (index == 0) {
                            scrollToIndex = -1 // 不需要滚动到任何位置
                        } else {
                            scrollToIndex = list.indexOf(areaCodeResp)
                            break
                        }
                    } else {
                        scrollToIndex = list.indexOf(areaCodeResp)
                        break
                    }
                }
            }
            if (scrollToIndex != -1) {
                mBinding.recycler.smoothScrollToPosition(scrollToIndex)
            }

        }

        mBinding.recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                //第一个可见的位置
                val layoutManager = recyclerView.layoutManager
                //判断是当前layoutManager是否为LinearLayoutManager
                // 只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
                var firstItemPosition = 0
                if (layoutManager is LinearLayoutManager) {
                    //获取第一个可见view的位置
                    firstItemPosition = layoutManager.findFirstVisibleItemPosition()
                }

                if (firstItemPosition >= 0) {
                    mBinding.sidebar.onItemScrollUpdateSideBarText(
                        mAdapter.data[firstItemPosition].firstLetter
                    )
                }
            }
        })

        mBinding.areaCodeEdit.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}

            override fun afterTextChanged(s: Editable?) {
                if (!TextUtils.isEmpty(s.toString())) {
                    val tempList = ArrayList<AreaCodeResp>()
                    tempList.clear()
                    list.forEach {
                        val isCountry = it.countryName?.contains(s.toString(), true) == true
                                || it.areaCode?.contains(s.toString(), true) == true

                        if (isCountry) {
                            tempList.add(it)
                        }
                    }
                    mAdapter.setIsSearch(true)
                    mAdapter.setList(tempList)
                    if (tempList.size == 0) {
                        mBinding.sidebar.visibility = View.GONE
                    } else {
                        mBinding.sidebar.visibility = View.VISIBLE
                    }
                } else {
                    mBinding.sidebar.visibility = View.VISIBLE
                    mAdapter.setIsSearch(false)
                    mAdapter.setList(list)
                }
            }
        })

        mAdapter.setOnItemClickListener { _, _, position ->
            if (mAdapter.data[position].areaCode != null) {
                val intent = Intent().apply {
                    putExtra("areaCode", mAdapter.data[position])
                }
                setResult(RESULT_OK, intent)
                finish()
            }
        }

    }

    fun getinitialList(list: List<AreaCodeResp>) {
        var lastIndexStr = ""
        list.forEach {
            it.firstLetter?.let { co ->
                if (lastIndexStr != co) {
                    initialList += co
                    lastIndexStr = co
                }
            }
        }
        if (initialList.isNotEmpty() && initialList[0] != "A") {
            initialList = initialList.drop(1).toTypedArray()
        }
        mBinding.sidebar.setDataList(initialList)
    }

    private fun initData() {
        mViewModel.allAreaCodeLiveData.observe(this) { areaCodes ->
            list.addAll(areaCodes)
            list.sortBy { it.countryName?.first()?.uppercaseChar() }
            var index = 0
            var tempItem: AreaCodeResp? = null
            list.forEachIndexed { position, areaCodeResp ->
                if (stringExtra == areaCodeResp.countryCode) {
                    index = position
                    tempItem = areaCodeResp
                }
            }

            val finalTempItem = tempItem
            if (finalTempItem != null) {
                list.removeAt(index)
                list.add(0, finalTempItem)
            } else {
                tempItem = AreaCodeResp(countryName = "none").apply {
                    list.add(0, this)
                }
            }
            getinitialList(list)
            mAdapter.setList(list)
        }

        mViewModel.getAllAreaCode()
    }
}

